<template>
  <div class="ai-ragflow-chat">
    <!-- AI图标按钮 -->
    <transition name="bounce">
      <div 
        v-show="!isOpen"
        class="ai-button" 
        @click="toggleChat"
        :class="{ 'ai-button-pulse': !hasInteracted }"
      >
        <i class="bi bi-robot"></i>
        <span class="ai-badge" v-if="!hasInteracted">New</span>
      </div>
    </transition>

    <!-- 聊天窗口 -->
    <transition name="slide-up">
      <div v-show="isOpen" class="chat-window">
        <!-- 窗口头部 -->
        <div class="chat-header">
          <div class="header-left">
            <i class="bi bi-robot header-icon"></i>
            <div class="header-title">
              <span class="title-text">RAGflow AI助手</span>
              <span class="status-dot" :class="{ 'status-online': !isLoading && !hasError }"></span>
            </div>
          </div>
          <div class="header-actions">
            <button class="header-btn" @click="minimizeChat" title="最小化">
              <i class="bi bi-dash-lg"></i>
            </button>
            <button class="header-btn" @click="closeChat" title="关闭">
              <i class="bi bi-x-lg"></i>
            </button>
          </div>
        </div>

        <!-- 聊天内容 -->
        <div class="chat-content">
          <!-- 加载状态 -->
          <div v-if="isLoading" class="loading-state">
            <div class="spinner"></div>
            <p>正在连接RAGflow AI...</p>
            <small>{{ loadingTip }}</small>
          </div>

          <!-- 错误状态 -->
          <div v-else-if="hasError" class="error-state">
            <i class="bi bi-exclamation-triangle error-icon"></i>
            <p>连接失败</p>
            <small>请检查RAGflow服务是否正常运行</small>
            <small class="error-url">{{ chatUrl }}</small>
            <button class="retry-btn" @click="retryConnection">
              <i class="bi bi-arrow-clockwise"></i> 重试连接
            </button>
          </div>

          <!-- RAGflow iframe -->
          <iframe
            v-show="!isLoading && !hasError"
            ref="chatIframe"
            :src="chatUrl"
            class="chat-iframe"
            frameborder="0"
            allow="microphone; camera"
            @load="handleIframeLoad"
            @error="handleIframeError"
          ></iframe>
        </div>

        <!-- 窗口底部 -->
        <div class="chat-footer">
          <span class="footer-text">Powered by RAGflow</span>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
export default {
  name: 'AIRAGflowChat',
  props: {
    // RAGflow共享ID
    sharedId: {
      type: String,
      default: 'ec1da38caef211f088ef72ae004f33d4'
    },
    // 认证token
    authToken: {
      type: String,
      default: 'Y3NjMyMmJhYjNmOTExZjBiMGY2MzJhNz'
    },
    // RAGflow服务地址
    baseUrl: {
      type: String,
      default: 'http://localhost'
    },
    // 语言设置
    locale: {
      type: String,
      default: 'zh'
    },
    // 窗口位置 (bottom-right, bottom-left, top-right, top-left)
    position: {
      type: String,
      default: 'bottom-right'
    }
  },
  data() {
    return {
      isOpen: false,
      isLoading: false,
      hasError: false,
      hasInteracted: false,
      loadTimeout: null,
      loadingTips: [
        '正在初始化AI助手...',
        '正在连接RAGflow服务...',
        '正在加载聊天界面...',
        '马上就好...'
      ],
      currentTipIndex: 0
    };
  },
  computed: {
    chatUrl() {
      return `${this.baseUrl}/next-chats/share?shared_id=${this.sharedId}&from=chat&auth=${this.authToken}&locale=${this.locale}`;
    },
    loadingTip() {
      return this.loadingTips[this.currentTipIndex];
    }
  },
  mounted() {
    // 循环显示加载提示
    this.tipInterval = setInterval(() => {
      this.currentTipIndex = (this.currentTipIndex + 1) % this.loadingTips.length;
    }, 2000);
  },
  beforeUnmount() {
    if (this.loadTimeout) {
      clearTimeout(this.loadTimeout);
    }
    if (this.tipInterval) {
      clearInterval(this.tipInterval);
    }
  },
  methods: {
    toggleChat() {
      this.isOpen = !this.isOpen;
      this.hasInteracted = true;
      
      if (this.isOpen) {
        this.isLoading = true;
        this.hasError = false;
        
        // 设置超时检测
        this.loadTimeout = setTimeout(() => {
          if (this.isLoading) {
            this.hasError = true;
            this.isLoading = false;
            console.error('RAGflow连接超时:', this.chatUrl);
          }
        }, 10000); // 10秒超时
      }
    },
    minimizeChat() {
      this.isOpen = false;
    },
    closeChat() {
      this.isOpen = false;
      // 可选：重置状态
      // this.isLoading = false;
      // this.hasError = false;
    },
    handleIframeLoad() {
      console.log('RAGflow iframe加载成功');
      this.isLoading = false;
      this.hasError = false;
      if (this.loadTimeout) {
        clearTimeout(this.loadTimeout);
      }
    },
    handleIframeError(error) {
      console.error('RAGflow iframe加载失败:', error);
      this.isLoading = false;
      this.hasError = true;
      if (this.loadTimeout) {
        clearTimeout(this.loadTimeout);
      }
    },
    retryConnection() {
      this.hasError = false;
      this.isLoading = true;
      
      // 重新加载iframe
      if (this.$refs.chatIframe) {
        this.$refs.chatIframe.src = this.chatUrl;
      }
      
      // 重新设置超时
      this.loadTimeout = setTimeout(() => {
        if (this.isLoading) {
          this.hasError = true;
          this.isLoading = false;
        }
      }, 10000);
    }
  }
};
</script>

<style scoped lang="less">
.ai-ragflow-chat {
  position: fixed;
  z-index: 9999;
  
  // 根据position属性定位
  &:has(.ai-button) {
    bottom: 30px;
    right: 30px;
  }
}

/* AI按钮样式 */
.ai-button {
  position: relative;
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 20px rgba(102, 126, 234, 0.5);
  transition: all 0.3s ease;
  
  i {
    font-size: 28px;
    color: white;
  }
  
  &:hover {
    transform: scale(1.1);
    box-shadow: 0 6px 30px rgba(102, 126, 234, 0.7);
  }
  
  &:active {
    transform: scale(0.95);
  }
}

/* 脉冲动画 */
.ai-button-pulse {
  animation: pulse 2s infinite;
}

@keyframes pulse {
  0% {
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.5);
  }
  50% {
    box-shadow: 0 4px 30px rgba(102, 126, 234, 0.8), 0 0 0 10px rgba(102, 126, 234, 0.2);
  }
  100% {
    box-shadow: 0 4px 20px rgba(102, 126, 234, 0.5);
  }
}

/* 新标签 */
.ai-badge {
  position: absolute;
  top: -5px;
  right: -5px;
  background: #ff4757;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  font-weight: bold;
  animation: bounce-badge 1s infinite;
}

@keyframes bounce-badge {
  0%, 100% { transform: translateY(0); }
  50% { transform: translateY(-3px); }
}

/* 聊天窗口 */
.chat-window {
  position: fixed;
  bottom: 100px;
  right: 30px;
  width: 400px;
  height: 600px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 窗口头部 */
.chat-header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 16px 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  user-select: none;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.header-icon {
  font-size: 24px;
}

.header-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title-text {
  font-weight: 600;
  font-size: 16px;
}

.status-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #95a5a6;
  animation: blink 2s infinite;
}

.status-online {
  background: #2ecc71;
}

@keyframes blink {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.5; }
}

.header-actions {
  display: flex;
  gap: 8px;
}

.header-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  
  i {
    font-size: 16px;
  }
  
  &:hover {
    background: rgba(255, 255, 255, 0.3);
  }
}

/* 聊天内容 */
.chat-content {
  flex: 1;
  position: relative;
  background: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chat-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background: white;
}

/* 加载状态 */
.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16px;
  color: #7f8c8d;
  
  p {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
  }
  
  small {
    font-size: 12px;
    color: #95a5a6;
  }
}

.spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #ecf0f1;
  border-top-color: #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

/* 错误状态 */
.error-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 12px;
  padding: 30px;
  text-align: center;
  
  .error-icon {
    font-size: 48px;
    color: #e74c3c;
  }
  
  p {
    margin: 0;
    font-size: 16px;
    font-weight: 500;
    color: #2c3e50;
  }
  
  small {
    font-size: 12px;
    color: #7f8c8d;
  }
  
  .error-url {
    font-family: monospace;
    background: #ecf0f1;
    padding: 8px 12px;
    border-radius: 6px;
    word-break: break-all;
    max-width: 100%;
  }
}

.retry-btn {
  margin-top: 16px;
  padding: 10px 24px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  }
  
  i {
    font-size: 16px;
  }
}

/* 窗口底部 */
.chat-footer {
  background: white;
  padding: 12px;
  text-align: center;
  border-top: 1px solid #ecf0f1;
}

.footer-text {
  font-size: 12px;
  color: #95a5a6;
}

/* 动画效果 */
.bounce-enter-active {
  animation: bounce-in 0.5s;
}

.bounce-leave-active {
  animation: bounce-out 0.3s;
}

@keyframes bounce-in {
  0% {
    transform: scale(0);
  }
  50% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes bounce-out {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(0);
  }
}

.slide-up-enter-active,
.slide-up-leave-active {
  transition: all 0.3s ease;
}

.slide-up-enter-from {
  transform: translateY(20px);
  opacity: 0;
}

.slide-up-leave-to {
  transform: translateY(20px);
  opacity: 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-window {
    width: calc(100vw - 40px);
    height: calc(100vh - 140px);
    right: 20px;
    bottom: 100px;
  }
  
  .ai-button {
    width: 55px;
    height: 55px;
    
    i {
      font-size: 24px;
    }
  }
}

@media (max-width: 480px) {
  .chat-window {
    width: 100vw;
    height: 100vh;
    right: 0;
    bottom: 0;
    border-radius: 0;
  }
  
  .ai-ragflow-chat {
    bottom: 20px;
    right: 20px;
  }
}
</style>

